package com.spring.demo1.eg3;

import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 实现SmartInstantiationAwareBeanPostProcessor来更改早期暴露的bean对象
 *
 * @author vhans
 */
@Component
public class MethodBeforeInterceptor implements SmartInstantiationAwareBeanPostProcessor {
    // 从3级缓存中获取bean的时候，会调用getEarlyBeanReference方法来获取bean，这个方法内部会看一下容器中是否有
    // SmartInstantiationAwareBeanPostProcessor这种处理器，然后会依次调用这种处理器中的getEarlyBeanReference 方法
    @Override
    public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
        if ("service1".equals(beanName)) {
            ProxyFactory proxyFactory = new ProxyFactory(bean);
            proxyFactory.addAdvice(new MethodBeforeAdvice() {
                @Override
                public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
                    System.out.println("你好,service1");
                }
            });
            return proxyFactory.getProxy();
        }
        return bean;
    }
}
